<?php
/**
 * Created by PhpStorm.
 * User: lixiaohui
 * Date: 2015/9/21
 * Time: 20:31
 */

namespace Home\Controller;


use Think\Controller;
use Think\Log;

/**
 * Class BindController
 * @package Home\Controller 绑定操作控制器
 */
class BindController extends Controller
{
    //绑定信息的首页
    public function index()
    {
        $openId = getOpenId();
        $relevanceTable = M('member_relevance');
        $relevanceModel = $relevanceTable->where("openId='%s'", $openId)->order('createtime desc')->select();
        //dump($relevanceModel);
        $this->assign('relevanceModel', $relevanceModel);
        $this->display();
    }

    /**
     * 新增绑定
     */
    public function add()
    {
        $this->display();
    }

    /**
     * 绑定水费账号 ajax
     */
    public function bind()
    {
        $data['name'] = I("name");
        $data['userid'] = I("account");
        $data['idnumber'] = I("number");
        $data['id'] = getUUIDShort();
        $data['openid'] = getOpenId();
        $data['createtime'] = array("exp", "now()");
        //调用验证接口的参数
        $verifyParamArr = array(
            "name" => $data['name'],
            "no" => $data['idnumber'],
            "userid" => $data['userid']
        );
        $postString = getPostString("GetVerifyYh", $verifyParamArr);
        //发送请求验证用户是否存在
        $retStr = post(C('INTERFACE_BASE_URL'), $postString);

        Log::write('参数:'.C('INTERFACE_BASE_URL').'?'.$postString);
        Log::write('返回串:'.$retStr);

        //生成数组对象
        $retObj = json_decode($retStr,true);
        //若不存在该用户
        if($retObj['retcode'] != '0'){
            $this -> ajaxReturn(array("status"=>"fail","msg"=>$retObj['errmsg']));
        }
        //判断是否已绑定过该水费
        $relevanceTable = M('member_relevance');

        $existResult = $relevanceTable -> where("openid='%s' and idnumber='%s'",getOpenId(),$data['idnumber']) ->select();

        if(count($existResult) > 0){
            $this -> ajaxReturn(array("status"=>"fail","msg"=> "您已绑定过'".$data['userid']."'账号,不能重复绑定!"));
        }
        //保存数据
        $saveResult = $relevanceTable -> add($data);
        if($saveResult > 0){
            $this -> ajaxReturn(array("status"=>"success","msg"=>"绑定成功!"));
        } else{
            $this -> ajaxReturn(array("status"=>"fail","msg"=>"绑定失败!"));
        }
    }

    /**
     * 删除已绑定的税费账号
     */
    public function delete()
    {
        $delResult = M('member_relevance')->where("openId='%s' and id='%s'", getOpenId(), I('id'))->delete();
        if ($delResult > 0) {
            $this->ajaxReturn(array("status" => "success", "msg" => "删除成功!"));
        } else {
            $this->ajaxReturn(array("status" => "fail", "msg" => "删除失败!"));
        }
    }
}